<template>
  <div class="uploadAnalysis">
    <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx,.xls" @change="handleClick">
    <el-button type="primary" @click="handleUpload">{{text}}</el-button>
  </div>
</template>

<script>
import XLSX from "xlsx";
import { client, randomWord } from "@/utils/alioss";
import { ElMessage } from 'element-plus'
export default {
  props: {
    cancelUpload: {//是否禁用上传，只解析数据
      type: Boolean,
      default: false,
    },
    text:{
      default:"上传文件",
      type: String,
    }
  },
  data() {
    return {
      // loading: false,
      excelData: {
        header: null,
        results: null,
      },
    };
  },
  methods: {
    handleUpload() {
      this.$refs["excel-upload-input"].click();
    },
    async handleClick(e) {
      console.log("files:",e.target.files);
      const files = e.target.files||[];
      const file = files[0];
      if (!file) return;
      // 1.上传
      if(!this.cancelUpload){
        this.$emit('onStep','beforeUpload',{name:file.name});
        let res=await this.uploadFile(file);
        this.$emit('onStep', "uploadSuccess", res);
      }
      // 2.解析
      let res2=await this.readerData(file);
      if(res2.code==='error'){
        this.$emit("onStep","analysisFail", res2);
      }else{
        this.$emit("onStep","analysisSuccess", res2);
      }
      // 清除文件
      e.target.value="";
    },
    
    // 上传文件
    uploadFile(file){
      return new Promise((resolve)=>{
        let fileName = `福利发放用户表${randomWord(true, 8)}_${Date.now()}.xlsx`;
        // let fileName="发放用户表-测试.xlsx"
        client().put("doc/"+fileName, file).then(res => {
          resolve(res);
        }).catch(err => {
          console.log(err)
        })
      });
    },

    // 解析文件
    readerData(file) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = e.target.result;
          const fixedData = this.fixData(data);
          const workbook = XLSX.read(btoa(fixedData), { type: "base64" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          let header;
          try {
            header=this.getHeaderRow(worksheet);
          } catch (error) {
            resolve({code:'error'});
          }
          const results = XLSX.utils.sheet_to_json(worksheet);
          resolve({header,results});
        };
        reader.readAsArrayBuffer(file);
      });
    },
    generateData({ header, results }) {
      this.excelData.header = header;
      this.excelData.results = results;
      if (results.length > 2000) {
        ElMessage({
          showClose: true,
          message: "当前文件数据量超过2000条限制，请重新上传",
          type: "warning",
        });
      } else {
        this.$emit("analysisSuccess",this.excelData);
      }
    },
    fixData(data) {
      let o = "";
      let l = 0;
      const w = 10240;
      for (; l < data.byteLength / w; ++l)
        o += String.fromCharCode.apply(
          null,
          new Uint8Array(data.slice(l * w, l * w + w))
        );
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
      return o;
    },
    getHeaderRow(sheet) {
      const headers = [];
      const range = XLSX.utils.decode_range(sheet["!ref"]);
      let C;
      const R = range.s.r;
      for (C = range.s.c; C <= range.e.c; ++C) {
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
        let hdr = "UNKNOWN " + C;
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        headers.push(hdr);
      }
      return headers;
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name);
    },
  },
};
</script>

<style scoped>
.uploadAnalysis{
  display: inline-block;
}
.uploadAnalysis .excel-upload-input {
  display: none;
  z-index: -1;
}
</style>
